//
//  RetreatViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/26.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "RetreatApplyViewController.h"
#import "WeChatLoginViewController.h"
@interface RetreatApplyViewController ()
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIView * upAlertView;//顶部提示背景
@property (nonatomic, strong)UIView * middleWhiteView;//中部白色背景
@property (nonatomic, strong)UIView * bottomWhiteView;//中部白色背景
@property (nonatomic, strong)UIImageView * produceImg;//商品图片
@property (nonatomic, strong)UILabel * produceTitleLab;//商品名
@property (nonatomic, strong)UILabel * priceLab;//金额
@property (nonatomic, strong)UILabel * numLab;//数量
@property (nonatomic, strong)UILabel * listNumLab;//订单编号
@property (nonatomic, strong)NSString * listID;//订单ID
@property (nonatomic, strong)NSString * addressID;//地址ID
@property (nonatomic, strong)UILabel * dateContentLabl;//订单时间
@property (nonatomic, strong)UITextView * remarkContentTextField;//备注信息
@property (nonatomic, strong)UIButton * submitBtn;//立即付款
@property (nonatomic, strong)NSString * totalMoney;//总金额
@property (nonatomic, strong)NSDictionary * modelData;
@property (nonatomic, strong)NSString * numString;//数量
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)ifLogin;
@end

@implementation RetreatApplyViewController(networking)
- (void)getListData{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"orderid":self.orderID
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/tuiDetails" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.modelData = responseObject[@"list"];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//提交申请
- (void)submitListRefund{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"ordernum":self.listNumLab.text,
                           @"reason":self.remarkContentTextField.text
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/orderTui" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            ShowMessage(@"提交成功");
            int64_t delayInSeconds = 1;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation RetreatApplyViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    [self getListData];//网络接口
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = getColor(mainColor);
    self.navigationItem.title = @"退款流程";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
    
    [self setUpBottomTabBarView];
    
}

#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = getColor(mainColor);
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE)];
        _headerView.backgroundColor = getColor(mainColor);
        [self setUpMiddleWhiteView];
        [self setUpBottomWhiteView];
    }return _headerView;
}
- (void)setUpMiddleWhiteView{
    //中部白色背景
    self.middleWhiteView = [[UIView alloc] init];
    self.middleWhiteView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:self.middleWhiteView];
    //商品图片
    self.produceImg = [[UIImageView alloc] init];
    self.produceImg.image = [UIImage imageNamed:@"YimiPlaceHolder"];
    [self.middleWhiteView addSubview:self.produceImg];
    //商品名
    self.produceTitleLab = [[UILabel alloc] init];
    [self label:self.produceTitleLab withFont:DEF_FontSize_14 withText:@"商品名称" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.middleWhiteView];
    self.produceTitleLab.numberOfLines = 0;
    self.produceTitleLab.lineBreakMode = 0;
    //商品价格
    self.priceLab = [[UILabel alloc] init];
    [self label:self.priceLab withFont:DEF_FontSize_15 withText:[NSString stringWithFormat:@"￥%@", @"4200"] withTextColor:getColor(mainRedColor) withTextAlignment:NSTextAlignmentLeft withView:self.middleWhiteView];
    //数量
    self.numLab = [[UILabel alloc] init];
    [self label:self.numLab withFont:DEF_FontSize_15 withText:[NSString stringWithFormat:@"X   %@", @"-"] withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentRight withView:self.middleWhiteView];
    //masonry
    __weak typeof (self)weakSelf = self;
    [self.middleWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.headerView);
        make.top.equalTo(weakSelf.headerView.mas_top).mas_offset(10/WIDTH_6_SCALE);
        make.height.mas_offset(150/WIDTH_6_SCALE);
    }];
    [self.produceImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.middleWhiteView.mas_left).mas_offset(25/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.middleWhiteView.mas_top).mas_offset(23/WIDTH_6_SCALE);
        make.width.height.mas_offset(111/WIDTH_6_SCALE);
    }];
    [self.produceTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.produceImg.mas_right).mas_offset(30/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.middleWhiteView.mas_top).mas_offset(26/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.middleWhiteView.mas_right).mas_offset(-16/WIDTH_6_SCALE);
        make.bottom.lessThanOrEqualTo(weakSelf.priceLab.mas_top).mas_offset(-10/WIDTH_6_SCALE);
    }];
    [self.priceLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.produceTitleLab.mas_left);
        make.bottom.equalTo(weakSelf.middleWhiteView.mas_bottom).mas_offset(-32/WIDTH_6_SCALE);
    }];
    [self.numLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.middleWhiteView.mas_right).mas_offset(-18/WIDTH_6_SCALE);
        make.top.bottom.equalTo(weakSelf.priceLab);
    }];
}
- (void)setUpBottomWhiteView{
    //底部白色背景
    self.bottomWhiteView = [[UIView alloc] init];
    self.bottomWhiteView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:self.bottomWhiteView];
    //订单编号标题
    UILabel * listTitleLab = [[UILabel alloc] init];
    [self label:listTitleLab withFont:DEF_FontSize_14 withText:@"订单编号" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.bottomWhiteView];
    //订单编号内容
    self.listNumLab = [[UILabel alloc] init];
    [self label:self.listNumLab withFont:DEF_FontSize_12 withText:@"---" withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentRight withView:self.bottomWhiteView];
    //订单下横线
    UIView * listBottomLine = [[UIView alloc] init];
    listBottomLine.backgroundColor = getColor(@"f7f7f7");
    [self.bottomWhiteView addSubview:listBottomLine];
    //下单时间标题
    UILabel * dateTitleLab = [[UILabel alloc] init];
    [self label:dateTitleLab withFont:DEF_FontSize_14 withText:@"下单时间" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.bottomWhiteView];
    //下单时间内容
    self.dateContentLabl = [[UILabel alloc] init];
    [self label:self.dateContentLabl withFont:DEF_FontSize_12 withText:@"---" withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentRight withView:self.bottomWhiteView];
    //下单下横线
    UIView * dateBottomLine = [[UIView alloc] init];
    dateBottomLine.backgroundColor = getColor(@"f7f7f7");
    [self.bottomWhiteView addSubview:dateBottomLine];
    //备注标题
    UILabel * remarkTitleLab = [[UILabel alloc] init];
    [self label:remarkTitleLab withFont:DEF_FontSize_14 withText:@"退货原因" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.dateContentLabl];
    //备注内容
    self.remarkContentTextField = [[UITextView alloc] init];
    self.remarkContentTextField.textAlignment = NSTextAlignmentRight;
    self.remarkContentTextField.userInteractionEnabled = YES;
    self.remarkContentTextField.font = DEF_FontSize_14;
    [self.bottomWhiteView addSubview:self.remarkContentTextField];
    //masonry
    __weak typeof (self)weakSelf = self;
    [self.bottomWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.headerView);
        make.top.equalTo(weakSelf.middleWhiteView.mas_bottom).mas_offset(10/WIDTH_6_SCALE);
        make.bottom.equalTo(weakSelf.remarkContentTextField.mas_bottom);
    }];
    [listTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.headerView.mas_left).mas_offset(20/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.bottomWhiteView.mas_top);
        make.height.mas_offset(57/WIDTH_6_SCALE);
    }];
    [self.listNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.headerView.mas_right).mas_offset(-20/WIDTH_6_SCALE);
        make.top.bottom.equalTo(listTitleLab);
    }];
    [listBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(listTitleLab.mas_left);
        make.right.equalTo(weakSelf.listNumLab.mas_right);
        make.height.mas_offset(1/WIDTH_6_SCALE);
        make.top.equalTo(listTitleLab.mas_bottom);
    }];
    [dateTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.with.height.equalTo(listTitleLab);
        make.top.equalTo(listBottomLine.mas_bottom);
    }];
    [self.dateContentLabl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.right.equalTo(weakSelf.listNumLab);
        make.top.equalTo(dateTitleLab.mas_top);
    }];
    [dateBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.left.equalTo(listBottomLine);
        make.top.equalTo(dateTitleLab.mas_bottom);
    }];
    [remarkTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.width.equalTo(dateTitleLab);
        make.top.equalTo(dateBottomLine.mas_bottom);
    }];
    [self.remarkContentTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.height.equalTo(weakSelf.dateContentLabl);
        make.centerY.equalTo(remarkTitleLab.mas_centerY);
        make.left.equalTo(remarkTitleLab.mas_right).mas_offset(10/WIDTH_6_SCALE);
        make.top.lessThanOrEqualTo(remarkTitleLab.mas_top);
    }];
}
- (void)setUpBottomTabBarView{
    UIView * bottomBar = [[UIView alloc] init];
    bottomBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBar];
    //提交订单
    UIButton * submitBtn = [[UIButton alloc] init];
    submitBtn.titleLabel.font = DEF_FontSize_15;
    [submitBtn setTitle:@"提交申请" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:submitBtn];
    submitBtn.userInteractionEnabled = NO;
    self.submitBtn = submitBtn;
    [self.submitBtn setBackgroundColor:getColor(mainRedColor)];
    self.submitBtn.userInteractionEnabled = YES;
    self.submitBtn.hidden = NO;
    //masonry
    __weak typeof (self)weakSelf = self;
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-BOTTOM_HEIGHT);
        make.height.mas_offset(49/WIDTH_6_SCALE);
    }];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(134/WIDTH_6_SCALE);
        make.right.equalTo(bottomBar.mas_right).mas_offset(-7/WIDTH_6_SCALE);
        make.top.equalTo(bottomBar.mas_top).mas_offset(7/WIDTH_6_SCALE);
        make.bottom.equalTo(bottomBar.mas_bottom).mas_offset(-7/WIDTH_6_SCALE);
    }];
}
- (void)setModelData:(NSDictionary *)modelData{
    _modelData = modelData;
    [self.produceImg sd_setImageWithURL:[NSURL URLWithString:modelData[@"goodsimg"]] placeholderImage:[UIImage imageNamed:@""]];
    self.produceTitleLab.text = modelData[@"goodsname"];
    self.priceLab.text = [NSString stringWithFormat:@"￥%@", modelData[@"goodsagencyprice"]];
    self.numLab.text = [NSString stringWithFormat:@"x  %@", modelData[@"goodssum"]];
    self.numString = modelData[@"goodssum"];
    self.listNumLab.text = modelData[@"ordernum"];
    self.dateContentLabl.text = [self ConvertStrToTime:modelData[@"createtime"]];
    self.listNumLab.text = modelData[@"ordernum"];
    self.listID = modelData[@"ordernum"];
    self.addressID = modelData[@"addressid"];
    self.totalMoney = modelData[@"totalmoney"];
}
#pragma mark - action
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
- (void)submitBtnClick:(UIButton *)sender{
    if ([self.remarkContentTextField.text isEqualToString:@""] || [self.remarkContentTextField.text length] == 0 || self.remarkContentTextField.text == nil) {
        ShowMessage(@"请填写退货原因");
        return;
    }
    int i = (int)[self textLength:self.remarkContentTextField.text];
    if (i>80) {
        ShowMessage(@"请填写内容少于80个字");
        return;
    }
    [self submitListRefund];//提交申请
}
//时间戳变为格式时间
- (NSString *)ConvertStrToTime:(NSString *)timeStr{
    long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    //    long long time=[timeStr longLongValue] / 1000;
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString*timeString=[formatter stringFromDate:date];
    return timeString;
}
//得到中英文混合字符串长度
- (NSUInteger)textLength: (NSString *) text{
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength;
    return unicodeLength;
}
@end
